/*
 * @Description:
 * @Author: fhw
 * @Date: 2022-08-10 14:19:20
 */
import { WebSocketGateway, SubscribeMessage, MessageBody, ConnectedSocket, WebSocketServer } from '@nestjs/websockets'
import { isNil } from 'ramda'
import { Server } from 'typeorm'
import { ConfigService } from '../config/config.service'
import { SocketIndexService } from './socket-index.service'

@WebSocketGateway({ cors: true, transports: ['websocket']  })
export class SocketIndexGateway {
  constructor(private readonly socketIndexService: SocketIndexService, public readonly configService: ConfigService) { }

  @WebSocketServer() server: Server
  handleConnection() {
    this.server.on('connect', () => {
      console.log('与服务器建立好友聊天链接')
      this.configService.setSocketio(this.server)
    })
  }
  disconnect() {
    this.server.on('disconnect', ({ userId }) => {
      if (isNil(userId)) return
      this.configService.delChatUser(userId)
    })
  }
  @SubscribeMessage('storeClientInfo')
  storeClientInfo(@MessageBody() { userId }, @ConnectedSocket() clinet) {
    if (isNil(userId)) return
    this.configService.setChatUser(userId, clinet.id)
  }
}
